/*
package com.itheima.dianming.task;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dianming.controller.CommonController;
import com.itheima.dianming.exception.BusinessException;
import com.itheima.dianming.pojo.domain.ModelInterface;
import com.itheima.dianming.pojo.domain.StuInterfaceTestLog;
import com.itheima.dianming.pojo.domain.StuProject;
import com.itheima.dianming.pojo.vo.R;
import com.itheima.dianming.service.ModelInterfaceService;
import com.itheima.dianming.service.StuProjectService;
import com.itheima.dianming.template.RunTemplate;
import com.itheima.dianming.util.Cmder;
import com.itheima.dianming.util.GitUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Component
@Slf4j
public class TaskCommondLineRunner implements CommandLineRunner {

    @Autowired
    private StuProjectService stuProjectService;

    @Autowired
    private ModelInterfaceService modelInterfaceService;

    @Value("${dingding.git.localPath}")
    private String localPath;

    @Autowired
    private RunTemplate runTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    ExecutorService executorService = Executors.newCachedThreadPool();

    @Value("${dingding.ruiji.logqueue}")
    private String queueName;

    @Override
    public void run(String... args) throws Exception {
        List<StuProject> list = stuProjectService.list();
        for (StuProject stuProject : list) {
            Long projectId = stuProject.getProjectId();
            Long stuId = stuProject.getStuId();
            log.info("开始执行代码，学生id：{}，项目id：{}",stuId,projectId);
            try{
                R r = init(projectId, stuId);
                log.info("执行结果，{}",r);
            }catch (Exception e){
                log.info("执行出错，{}",e.getMessage());
            }
        }
    }

    private R init(Long pid, Long stuId){
        String localPathTemp = localPath+"\\"+stuId;
        StuInterfaceTestLog testLog = new StuInterfaceTestLog(null,stuId,pid,0L,"开始清空文件夹");
        if(FileUtil.exist(localPathTemp)){
            log.info("文件夹存在{}",localPathTemp);
        }else {
            log.info("文件夹不存在{}",localPathTemp);
            FileUtil.mkdir(localPathTemp);
        }
        //1、获取该学生的项目信息
        LambdaQueryWrapper<StuProject> qw = new LambdaQueryWrapper<>();
        qw.eq(StuProject::getProjectId,pid);
        qw.eq(StuProject::getStuId,stuId);
        StuProject stuProject = stuProjectService.getOne(qw);
        if(stuProject==null){
            return R.onflag(false,"该学生项目信息不存在");
        }
        String gitUrl = stuProject.getGitUrl();
        String branchName = stuProject.getBranchName();
        //第一步、克隆代码
        log.info("第一步、克隆或者拉取代码");
        testLog.setStep(1L);
        testLog.setDetail("第一步、克隆代码");
        try {
            GitUtils.gitClone(gitUrl,branchName,localPathTemp);
        } catch (Exception e) {
            e.printStackTrace();
            testLog.setDetail("ERROR,克隆代码，出错:"+e.getMessage());
            rabbitTemplate.convertAndSend(queueName,testLog);
            return R.onflag(false,"第一步、克隆代码，出错");
        }
        rabbitTemplate.convertAndSend(queueName,testLog);

        //第二步：执行 mvn package 打包命令
        try {
            log.info("cmd /C C: &  cd "+localPathTemp+" &  mvn package");
            String s = Cmder.executeCmdCommand("cmd /C C: &  cd " + localPathTemp + " &  mvn package  -DskipTests");
            testLog.setStep(2L);
            testLog.setDetail("第二步：打包,mvn package  ====>"+s);
            if(s.contains("ERROR")){
                testLog.setDetail("ERROR,第二步：打包,mvn package  ====>"+s);
                rabbitTemplate.convertAndSend(queueName,testLog);
                throw new BusinessException("打包出错！");
            }
            rabbitTemplate.convertAndSend(queueName,testLog);
        } catch (IOException e) {
            e.printStackTrace();
            testLog.setStep(2L);
            testLog.setDetail("ERROR,第二步：打包====>"+e.getMessage());
            rabbitTemplate.convertAndSend(queueName,testLog);
            return R.onflag(false,"第二步：执行 mvn package 打包命令，出错");
        }
        //第三步：执行java -jar reggie.jar 运行程序


        List<String> resources = FileUtil.listFileNames(localPathTemp + "\\src\\main\\resources");
        if(!resources.contains("application-prod.yml")){
            testLog.setStep(3L);
            testLog.setDetail("ERROR,第三步：运行程序出错，没有配置application-prod.yml开发环境！");
            rabbitTemplate.convertAndSend(queueName,testLog);
            throw new BusinessException("没有配置application-prod.yml开发环境！");
        }
        List<String> fileList = FileUtil.listFileNames(localPathTemp+"\\target");
        boolean hasJar = false;
        Map signal =new HashMap();
        for (String name : fileList) {
            if(name.contains(".jar")){
                hasJar=true;
                log.info("cmd /C C: &  cd "+localPathTemp+"\\target & java -jar "+name);

                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String s = Cmder.executeCmdCommand("cmd /C C: &  cd " + localPathTemp + "\\target & java -jar " + name+" --spring.profiles.active=prod");
                            testLog.setStep(3L);
                            testLog.setDetail("第三步：运行程序： java -jar "+name+"========>"+s);
                            if(s.contains("Exception")){
                                testLog.setDetail("ERROR,第三步：运行程序： java -jar "+name+"========>"+s);
                                rabbitTemplate.convertAndSend(queueName,testLog);
                                signal.put("flag",s);
                                throw new BusinessException("远程程序出错！");
                            }
                            rabbitTemplate.convertAndSend(queueName,testLog);
                        } catch (IOException e) {
                            signal.put("flag",e.getMessage());
                            e.printStackTrace();
                            testLog.setStep(3L);
                            testLog.setDetail("ERROR,第三步：运行程序： java -jar "+name+"========>"+e.getMessage());
                            rabbitTemplate.convertAndSend(queueName,testLog);
                            log.error("第三步：执行java -jar reggie.jar 运行程序，出错");
                        }
                    }
                });

            }
        }
        if(!hasJar){
            log.info("打包方式不对！！");
            testLog.setStep(2L);
            testLog.setDetail("ERROR,打包， mvn package  ====>打包方式不对！！");
            rabbitTemplate.convertAndSend(queueName,testLog);
            throw new BusinessException("打包方式不对！！");
        }

        //第四步：获取项目的接口数据，开始执行所有接口的测试
        LambdaQueryWrapper<ModelInterface> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(ModelInterface::getProjectId,pid);
        qw1.orderByAsc(ModelInterface::getId);
        List<ModelInterface> list = modelInterfaceService.list(qw1);
        //检查是否启动
        int i=0;
        boolean isOk=false;
        while (i<=10){
            Object o = signal.get("flag");
            if(o!=null){
                testLog.setStep(3L);
                testLog.setDetail("ERROR,第三步：运行程序出错，"+o);
                rabbitTemplate.convertAndSend(queueName,testLog);
                throw new BusinessException("程序启动出错！");
            }
            try {
                log.info("第{}次8080端口是否启动:{}",i,new Date());
                boolean port = Cmder.findPort(8080);
                if(port){
                    isOk = true;
                    break;
                }
                Thread.sleep(i*1000);
                i++;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if(!isOk){
            throw new BusinessException("程序启动失败！！");
        }

        log.info("第四步：开始测试项目{}的所有接口，共{}",pid,list.size());
        testLog.setStep(4L);
        testLog.setDetail("第四步：开始执行项目的所有接口，共"+list.size()+"个接口");
        rabbitTemplate.convertAndSend(queueName,testLog);
        runTemplate.runModules(pid,list);
        testLog.setStep(6L);
        testLog.setDetail("所有接口测试完毕");
        rabbitTemplate.convertAndSend(queueName,testLog);
        return R.data(null);
    }
}
*/
